package ch.bfh.abcm.rems.display.subpanels.history;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.util.Observable;
import java.util.Observer;

import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.border.Border;

import ch.bfh.abcm.rems.controller.MessageElement;

public class HistoryPanel extends JPanel implements Observer {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;


    private JList<String> jlist;
    private JScrollPane jscrollPane;
    private DefaultListModel<String> listModel;

    public HistoryPanel(int width, int height) {

        this.setLayout(new BorderLayout());
        this.setPreferredSize(new Dimension(width, height));
        this.setBackground(Color.BLACK);

        this.listModel = new DefaultListModel<String>();
        this.jlist = new JList<String>(listModel);
        this.jscrollPane = new JScrollPane(jlist);
        this.jscrollPane.setPreferredSize(new Dimension(width, height));

        Border border = BorderFactory.createLineBorder(Color.BLACK);
        jscrollPane.setBorder(border);
        jscrollPane.setFont(new Font("Verdana", Font.BOLD, 12));
        this.add(new TitlePanel(), BorderLayout.NORTH);
        this.add(jscrollPane, BorderLayout.CENTER);
        this.add(createClearHistoryButton(), BorderLayout.SOUTH);
        setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

    }

    private JButton createClearHistoryButton() {
        ImageIcon buttonPic = new ImageIcon("buttonPic.png");
        JButton button = new JButton(buttonPic);
        button.setBackground(Color.BLACK);
        button.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                listModel.removeAllElements();
            }
        });
        return button;
    }

    @Override
    public void update(Observable o, Object arg) {
        MessageElement element = (MessageElement) arg;
        String[] lines = element.getMessage().split("\n");
        for (int i = 0; i < lines.length; i++) {
            listModel.addElement(lines[i]);
        }
        addSpaceInList();

        jscrollPane.getVerticalScrollBar().addAdjustmentListener(new AdjustmentListener() {
            public void adjustmentValueChanged(AdjustmentEvent e) {
                e.getAdjustable().setValue(e.getAdjustable().getMaximum());
            }
        });
    }

    private void addSpaceInList() {
        listModel.addElement(" ");
    }

}
